package com.example.li.view;

import android.content.Intent;
import android.graphics.Color;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.bigkoo.pickerview.TimePickerView;
import com.example.li.ACache;
import com.example.li.bean.LocationInfo;
import com.example.li.bean.MessageEvent;
import com.example.li.fllowstep.R;
import com.example.li.utils.CameraManager;
import com.example.li.utils.LocationUtil;
import com.loonggg.lib.alarmmanager.clock.AlarmManagerUtil;
import com.loonggg.lib.alarmmanager.clock.SendMessageEvent;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView date_tv;
    private TimePickerView pvTime;
    private RelativeLayout repeat_rl, ring_rl;
    private TextView tv_repeat_value, tv_ring_value;
    private LinearLayout allLayout;
    private Button set_btn;
    private String time;
    private int cycle;
    private int ring;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationInfo mlocationinfo;
    private SurfaceView frontSurfaceView;
    private SurfaceHolder frontHolder;
    private boolean isFrontOpened = false;
    private Camera mFrontCamera;
    private CameraManager frontCameraManager;
    private EditText mEt_phone, etPwd;
    private String mImgurl;
    private ImageView mIv_photo;
    private Button quit_btn;
    private RadioGroup radioGroup;
    private ACache aCache;
    private List<LatLng> points = new ArrayList<>();
    private long start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        aCache = ACache.get(getApplicationContext());
        initView();
        setCamera();
        setListener();
        initLocation();


    }

    private void setCamera() {
        frontSurfaceView = findViewById(R.id.front_surfaceview);
        frontHolder = frontSurfaceView.getHolder();
        frontCameraManager = new CameraManager(mFrontCamera, frontHolder, this);
    }

    private Camera.AutoFocusCallback mAutoFocus = new Camera.AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            //TODO:空实现
        }
    };
    /*@Subscribe(threadMode = ThreadMode.Async)
    public void takePhoto(SendMessageEvent event) {
        *//*new Thread(new Runnable() {
            @Override
            public void run() {
                takeFrontPhoto();
            }
        }).start();*//*

    }*/

    private boolean takeFrontPhoto() {
        if (!isFrontOpened && frontCameraManager.openCamera(Camera.CameraInfo.CAMERA_FACING_FRONT)) {
            try {
                //因为开启摄像头需要时间，这里让线程睡2秒
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            //拍照
            mFrontCamera = frontCameraManager.getCamera();
            //自动对焦
            mFrontCamera.autoFocus(mAutoFocus);
            isFrontOpened = true;
            // 拍照
            mFrontCamera.takePicture(null, null, frontCameraManager.new PicCallback(mFrontCamera));
            return true;
        } else {
            return false;
        }
    }

    private void setLocation() {
        UiSettings mUisettings = mBaiduMap.getUiSettings();
        mUisettings.setOverlookingGesturesEnabled(false);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(Float.parseFloat(mlocationinfo.getRadius()))
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(Double.parseDouble(mlocationinfo.getLatitude()))
                .longitude(Double.parseDouble(mlocationinfo.getLontitude())).build();

        // 设置定位数据
        mBaiduMap.setMyLocationData(locData);

        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.icon_mark);
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, bitmap);
        mBaiduMap.setMyLocationConfiguration(config);
        LatLng ll = new LatLng(Double.parseDouble(mlocationinfo.getLatitude()), Double.parseDouble(mlocationinfo.getLontitude()));
        MapStatus.Builder builder = new MapStatus.Builder();
        //设置缩放中心点；缩放比例；
        builder.target(ll).zoom(18.0f);
        //给地图设置状态
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                points.add(mapStatus.target);
                Log.d("change", mapStatus.target.latitude + "\n" + mapStatus.target.longitude);
            }
        });


        // 当不需要定位图层时关闭定位图层
//        mBaiduMap.setMyLocationEnabled(false);
    }

    private void initLocation() {
        LocationUtil.getInstance().startLocation();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    private void initView() {
        mIv_photo = findViewById(R.id.iv_photo);
        mEt_phone = findViewById(R.id.et_phone);
        etPwd = findViewById(R.id.et_pwd);
        allLayout = (LinearLayout) findViewById(R.id.all_layout);
        set_btn = (Button) findViewById(R.id.set_btn);
        set_btn.setOnClickListener(this);
        date_tv = (TextView) findViewById(R.id.date_tv);
        repeat_rl = (RelativeLayout) findViewById(R.id.repeat_rl);
        repeat_rl.setOnClickListener(this);
        ring_rl = (RelativeLayout) findViewById(R.id.ring_rl);
        ring_rl.setOnClickListener(this);
        quit_btn = findViewById(R.id.quit_btn);
        quit_btn.setOnClickListener(this);
        tv_repeat_value = (TextView) findViewById(R.id.tv_repeat_value);
        tv_ring_value = (TextView) findViewById(R.id.tv_ring_value);
        mMapView = findViewById(R.id.bmapview);
        mBaiduMap = mMapView.getMap();
        pvTime = new TimePickerView(this, TimePickerView.Type.HOURS_MINS);
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        radioGroup = findViewById(R.id.rg);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.d("rg", i + "");
                aCache.put("mode", i + "");
            }
        });
    }

    private void setListener() {
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                time = getTime(date);
                date_tv.setText(time);
            }
        });

        date_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pvTime.show();
            }
        });
    }

    /**
     * 接收定位消息
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onShowMessageEvent(MessageEvent messageEvent) {
        mlocationinfo = messageEvent.getInfo();
        Log.d("main", mlocationinfo.toString() + mlocationinfo.getAddr());
        setLocation();

    }

    /*@Subscribe(threadMode = ThreadMode.MainThread)
    public void onShowColorUrl(SendMessageEvent messageEvent) {
        Log.d("test",messageEvent.toString());
        if(messageEvent.isColorMsg()){
            mImgurl = messageEvent.getBody();
            mIv_photo.setImageURI(Uri.fromFile(new File(mImgurl)));
            Log.d("main", messageEvent.getBody() + "aaaa");
        }
    }*/


    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.repeat_rl:
                selectRemindCycle();
                break;
            case R.id.ring_rl:
                selectRingWay();
                break;
            case R.id.set_btn:
                setClock();

                /*//test
                start = System.currentTimeMillis();
                double lat = Double.parseDouble(mlocationinfo.getLatitude());
                double lon = Double.parseDouble(mlocationinfo.getLontitude());
                for (int i = 0; i < 1; i++) {
                    points.add(new LatLng(lat - i, lon + i));
                }
                drawPath();*/
                break;
            case R.id.quit_btn:
                quitClock();
                break;
            default:
                break;
        }
    }

    private void setClock() {
        String pwd = etPwd.getText().toString();
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(getApplicationContext(), "请填写密码", Toast.LENGTH_SHORT).show();
            return;
        }
        start = System.currentTimeMillis();
        aCache.put("pwd", pwd);
        if (time != null && time.length() > 0) {
            String[] times = time.split(":");
            if (cycle == 0) {//是每天的闹钟
                AlarmManagerUtil.setAlarm(this, 0, Integer.parseInt(times[0]), Integer.parseInt
                        (times[1]), 0, 0, "闹钟响了", ring);
            }
            if (cycle == -1) {//是只响一次的闹钟
                AlarmManagerUtil.setAlarm(this, 1, Integer.parseInt(times[0]), Integer.parseInt
                        (times[1]), 0, 0, "闹钟响了", ring);
            } else {//多选，周几的闹钟
                String weeksStr = parseRepeat(cycle, 1);
                String[] weeks = weeksStr.split(",");
                for (int i = 0; i < weeks.length; i++) {
                    AlarmManagerUtil.setAlarm(this, 2, Integer.parseInt(times[0]), Integer
                            .parseInt(times[1]), i, Integer.parseInt(weeks[i]), "闹钟响了", ring);
                }
            }
            Toast.makeText(this, "闹钟设置成功", Toast.LENGTH_LONG).show();
        }

    }

    private void quitClock() {
        if (cycle == 0) {//是每天的闹钟
            AlarmManagerUtil.cancelAlarm(this, AlarmManagerUtil.ALARM_ACTION, 0);
        }
        if (cycle == -1) {//是只响一次的闹钟
            AlarmManagerUtil.cancelAlarm(this, AlarmManagerUtil.ALARM_ACTION, 0);
        } else {//多选，周几的闹钟
            String weeksStr = parseRepeat(cycle, 1);
            String[] weeks = weeksStr.split(",");
            for (int i = 0; i < weeks.length; i++) {
                AlarmManagerUtil.cancelAlarm(this, AlarmManagerUtil.ALARM_ACTION, i);
            }
        }
        Toast.makeText(this, "闹钟取消成功", Toast.LENGTH_LONG).show();
    }


    public void selectRemindCycle() {
        final SelectRemindCyclePopup fp = new SelectRemindCyclePopup(this);
        fp.showPopup(allLayout);
        fp.setOnSelectRemindCyclePopupListener((flag, ret) -> {
            switch (flag) {
                // 星期一
                case 0:

                    break;
                // 星期二
                case 1:

                    break;
                // 星期三
                case 2:

                    break;
                // 星期四
                case 3:

                    break;
                // 星期五
                case 4:

                    break;
                // 星期六
                case 5:

                    break;
                // 星期日
                case 6:

                    break;
                // 确定
                case 7:
                    int repeat = Integer.valueOf(ret);
                    tv_repeat_value.setText(parseRepeat(repeat, 0));
                    cycle = repeat;
                    fp.dismiss();
                    break;
                case 8:
                    tv_repeat_value.setText("每天");
                    cycle = 0;
                    fp.dismiss();
                    break;
                case 9:
                    tv_repeat_value.setText("只响一次");
                    cycle = -1;
                    fp.dismiss();
                    break;
                default:
                    break;
            }
        });
    }


    public void selectRingWay() {
        SelectRemindWayPopup fp = new SelectRemindWayPopup(this);
        fp.showPopup(allLayout);
        fp.setOnSelectRemindWayPopupListener(flag -> {
            switch (flag) {
                // 震动
                case 0:
                    tv_ring_value.setText("震动");
                    ring = 0;
                    break;
                // 铃声
                case 1:
                    tv_ring_value.setText("铃声");
                    ring = 1;
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * @param repeat 解析二进制闹钟周期
     * @param flag   flag=0返回带有汉字的周一，周二cycle等，flag=1,返回weeks(1,2,3)
     * @return
     */
    public static String parseRepeat(int repeat, int flag) {
        String cycle = "";
        String weeks = "";
        if (repeat == 0) {
            repeat = 127;
        }
        if (repeat % 2 == 1) {
            cycle = "周一";
            weeks = "1";
        }
        if (repeat % 4 >= 2) {
            if ("".equals(cycle)) {
                cycle = "周二";
                weeks = "2";
            } else {
                cycle = cycle + "," + "周二";
                weeks = weeks + "," + "2";
            }
        }
        if (repeat % 8 >= 4) {
            if ("".equals(cycle)) {
                cycle = "周三";
                weeks = "3";
            } else {
                cycle = cycle + "," + "周三";
                weeks = weeks + "," + "3";
            }
        }
        if (repeat % 16 >= 8) {
            if ("".equals(cycle)) {
                cycle = "周四";
                weeks = "4";
            } else {
                cycle = cycle + "," + "周四";
                weeks = weeks + "," + "4";
            }
        }
        if (repeat % 32 >= 16) {
            if ("".equals(cycle)) {
                cycle = "周五";
                weeks = "5";
            } else {
                cycle = cycle + "," + "周五";
                weeks = weeks + "," + "5";
            }
        }
        if (repeat % 64 >= 32) {
            if ("".equals(cycle)) {
                cycle = "周六";
                weeks = "6";
            } else {
                cycle = cycle + "," + "周六";
                weeks = weeks + "," + "6";
            }
        }
        if (repeat / 64 == 1) {
            if ("".equals(cycle)) {
                cycle = "周日";
                weeks = "7";
            } else {
                cycle = cycle + "," + "周日";
                weeks = weeks + "," + "7";
            }
        }

        return flag == 0 ? cycle : weeks;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mMapView.onDestroy();
    }

    /*@Subscribe(threadMode = ThreadMode.MainThread)
    public void sendColorMsg(SendMessageEvent event) {
        if(TextUtils.isEmpty(event.getBody())){
            return;
        }
        if(event.isColorMsg()){
            String mEtphone = mEt_phone.getText().toString().trim();
            Uri uri = null;
            mImgurl = event.getBody();
            if (mImgurl != null) {
//            uri = Uri.parse(mImgurl);   //图片路径
                uri = Uri.fromFile(new File(mImgurl));   //图片路径
            }
            Log.d("sendColorMsg", mImgurl);
            mIv_photo.setImageURI(uri);
//        return;
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, uri);// uri为你的附件的uri
            intent.putExtra("subject", "it's subject"); //彩信的主题
            intent.putExtra("address", mEtphone); //彩信发送目的号码
            intent.putExtra("sms_body", "it's content"); //彩信中文字内容
            intent.putExtra(Intent.EXTRA_TEXT, "it's EXTRA_TEXT");
            intent.setType("image/*");// 彩信附件类型
            intent.setClassName("com.android.mms","com.android.mms.ui.ComposeMessageActivity");
            try {
                startActivity(intent);
            }catch (Exception e) {
                intent = new Intent(Intent.ACTION_SEND);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(Intent.EXTRA_STREAM, uri);// uri为你的附件的uri
                intent.putExtra("subject", "it's subject"); //彩信的主题
                intent.putExtra("address", mEtphone); //彩信发送目的号码
                intent.putExtra("sms_body", "it's content"); //彩信中文字内容
                intent.putExtra(Intent.EXTRA_TEXT, "it's EXTRA_TEXT");
                intent.setType("image/*");// 彩信附件类型
                startActivity(intent);
            }
        }

    }*/
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void sendmessage(SendMessageEvent event) {
        Log.d("test", event.toString());
        if (event.isColorMsg()) {
            if (TextUtils.isEmpty(event.getBody())) {
                /*new Thread(new Runnable() {
                    @Override
                    public void run() {
                        takeFrontPhoto();
                    }
                }).start();*/
                takeFrontPhoto();

            } else {
                drawPath();
                String mEtphone = mEt_phone.getText().toString().trim();
                Uri uri = null;
                mImgurl = event.getBody();
                if (mImgurl != null) {
//            uri = Uri.parse(mImgurl);   //图片路径
                    uri = Uri.fromFile(new File(mImgurl));   //图片路径
                }
                Log.d("sendColorMsg", mImgurl);
                mIv_photo.setImageURI(uri);
//        return;
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(Intent.EXTRA_STREAM, uri);// uri为你的附件的uri
                intent.putExtra("subject", "it's subject"); //彩信的主题
                intent.putExtra("address", mEtphone); //彩信发送目的号码
                intent.putExtra("sms_body", "it's content"); //彩信中文字内容
                intent.putExtra(Intent.EXTRA_TEXT, "it's EXTRA_TEXT");
                intent.setType("image/*");// 彩信附件类型
                intent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    intent = new Intent(Intent.ACTION_SEND);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(Intent.EXTRA_STREAM, uri);// uri为你的附件的uri
                    intent.putExtra("subject", "it's subject"); //彩信的主题
                    intent.putExtra("address", mEtphone); //彩信发送目的号码
                    intent.putExtra("sms_body", "it's content"); //彩信中文字内容
                    intent.putExtra(Intent.EXTRA_TEXT, "it's EXTRA_TEXT");
                    intent.setType("image/*");// 彩信附件类型
                    startActivity(intent);
                }
            }
        } else {
            String mEtphone = mEt_phone.getText().toString().trim();
            SmsManager smsManager = SmsManager.getDefault();
            if (mlocationinfo.getAddr() != null) {
                drawPath();
                smsManager.sendTextMessage(mEtphone, null, mlocationinfo.getAddr() + "", null, null);
            } else {
                Toast.makeText(this, "未获取到定位信息", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //画路径
    private void drawPath() {
        /*double lat = Double.parseDouble(mlocationinfo.getLatitude());
        double lon = Double.parseDouble(mlocationinfo.getLontitude());
        for (int i = 0; i < 10; i++) {
            points.add(new LatLng(lat - i,lon + i));
        }*/
        if (points.size() < 2) {
            return;
        } else {
            PolylineOptions options = new PolylineOptions().color(0xAAFF0000).width(15)
                    .points(points);
            mBaiduMap.addOverlay(options);
        }

        double lat, lon;
        double distance;
        if (points.size() <= 1) {
            lat = 0;
            lon = 0;
            distance = 0;
        } else {
            LatLng latLng = points.get(points.size() - 1);
            lat = latLng.latitude - points.get(0).latitude;
            lon = latLng.longitude - points.get(0).longitude;
            distance = DistanceUtil.getDistance(points.get(0), latLng);
        }
        long time = (System.currentTimeMillis() - start) / 1000;
        StringBuilder stringBuilder = new StringBuilder("距离：" + String.format("%.2f", distance) + "km").append("\n")
                .append("时间：" + (time / 60) + "分钟\t")
                .append("平均速度：" + String.format("%.2f", distance / time) + "m/s").append("\n")
                .append("经度：" + String.format("%.2f", lat) + "纬度：" + String.format("%.2f", lon)).append("\n");
        TextView textView = new TextView(getApplicationContext());
        textView.setPadding(15, 15, 8, 35);
        textView.setTextColor(Color.WHITE);
        textView.setBackgroundColor(Color.BLUE);
        textView.setText(stringBuilder);
        textView.setTextSize(12);
        InfoWindow mInfoWindow = new InfoWindow(textView, points.get(points.size() - 1), 0);
        //显示InfoWindow
        mBaiduMap.showInfoWindow(mInfoWindow);
    }

}
